<script setup>
import { ref, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useAuthStore } from './stores/auth'
import TabsView from './components/TabsView.vue'
import { hasPermission } from './utils/auth'
import { 
  Menu as IconMenu, 
  Setting as IconSetting, 
  Service as IconService,
  HomeFilled as IconHome,
  ArrowDown,
  Fold,
  Expand,
  SwitchButton,
  User as IconUser,
  Lock as IconLock,
  UserFilled as IconUserFilled,
  OfficeBuilding
} from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()
const isCollapse = ref(false)
const asideWidth = computed(() => isCollapse.value ? '64px' : '220px')

// 判断是否是登录页
const isLoginPage = computed(() => route.path === '/login')

// Menu section names and icons
const menuItems = [
  { id: 'home', path: '/', label: '首页', icon: IconHome },
  { id: 'apps', path: '/apps', label: 'RPA应用管理', icon: IconMenu, permission: 'app:view' },
  { id: 'tasks', path: '/tasks', label: 'RPA运行管理', icon: IconSetting, permission: 'task:view' },
  { id: 'robots', path: '/robots', label: 'RPA机器人管理', icon: IconService, permission: 'robot:view' },
  { 
    id: 'permissions', 
    label: '权限管理', 
    icon: IconLock,
    permission: '*',
    children: [
      { id: 'users', path: '/users', label: '用户管理', icon: IconUser, permission: '*' },
      { id: 'roles', path: '/roles', label: '角色管理', icon: IconUserFilled, permission: '*' },
      { id: 'organizations', path: '/organizations', label: '组织管理', icon: OfficeBuilding, permission: '*' }
    ]
  }
]

// 过滤有权限的菜单项(包括子菜单)
const filteredMenuItems = computed(() => {
  return menuItems.filter(item => {
    // 如果没有设置权限，或用户有权限，则显示
    const hasItemPermission = !item.permission || hasPermission(item.permission)
    
    // 如果有子菜单，需要检查子菜单的权限
    if (item.children) {
      // 过滤有权限的子菜单
      const filteredChildren = item.children.filter(child => 
        !child.permission || hasPermission(child.permission)
      )
      
      // 如果至少有一个子菜单有权限，则显示父菜单
      if (filteredChildren.length > 0) {
        // 替换原始子菜单为过滤后的子菜单
        item.children = filteredChildren
        return true
      }
      return false
    }
    
    return hasItemPermission
  })
})

// 修改activeMenuItem的定义方式，添加watch来确保路由变化时菜单项能正确高亮
const activeMenuItem = ref('/')

// 监听路由变化，更新当前激活的菜单项
watch(() => route.path, (newPath) => {
  // 寻找匹配的菜单项，包括子菜单
  let matchedItem = null
  
  // 先搜索主菜单
  matchedItem = menuItems.find(item => 
    item.path && (newPath === item.path || (newPath.startsWith(item.path) && item.path !== '/'))
  )
  
  // 如果没找到，则搜索子菜单
  if (!matchedItem) {
    for (const item of menuItems) {
      if (item.children) {
        const childMatch = item.children.find(child => 
          newPath === child.path || (newPath.startsWith(child.path) && child.path !== '/')
        )
        if (childMatch) {
          matchedItem = childMatch
          break
        }
      }
    }
  }
  
  // 如果找到匹配项，更新激活菜单
  if (matchedItem && matchedItem.path) {
    activeMenuItem.value = matchedItem.path
  } else {
    // 如果是根路径或未找到匹配项，返回首页
    activeMenuItem.value = '/'
  }
}, { immediate: true })

// Navigate to route when menu item is clicked
const handleMenuSelect = (index) => {
  router.push({ path: index })
}

// Get breadcrumb items based on current route
const breadcrumbItems = computed(() => {
  const home = { path: '/', label: '首页', icon: IconHome }
  
  if (route.path === '/') {
    return [home, home]
  }

  // Find the current section
  const currentSection = menuItems.find(item => 
    item.id === route.path.split('/')[1]
  ) || { label: 'RPA管理系统' }
  
  return [home, currentSection]
})

// 处理登出
const handleLogout = () => {
  authStore.logout()
}

// 用户名显示
const userName = computed(() => {
  return authStore.user ? authStore.user.username : 'Admin'
})

// 用户角色显示
const userRole = computed(() => {
  return authStore.user ? authStore.user.role : 'unknown'
})

// 用户头像
const userAvatar = computed(() => {
  return authStore.user ? authStore.user.avatar : 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
})

// 导航到用户管理
const navigateToUsers = () => {
  router.push('/users')
}

// 导航到角色管理
const navigateToRoles = () => {
  router.push('/roles')
}

// 导航到组织管理
const navigateToOrganizations = () => {
  router.push('/organizations')
}
</script>

<template>
  <!-- 根布局 -->
  <div class="app-container">
    <!-- 主应用布局 - 只在已认证且非登录页面时显示 -->
    <template v-if="!isLoginPage && authStore.isAuthenticated">
      <el-container class="layout-container">
        <!-- Sidebar -->
        <el-aside :width="asideWidth" class="sidebar">
          <div class="logo-container">
            <h2 v-show="!isCollapse">RPA 管理系统</h2>
            <h2 v-show="isCollapse">RPA</h2>
          </div>
          
          <!-- Sidebar Menu -->
          <el-menu
            class="sidebar-menu"
            :default-active="activeMenuItem"
            :collapse="isCollapse"
            @select="handleMenuSelect"
            :unique-opened="true"
          >
            <template v-for="item in filteredMenuItems" :key="item.id">
              <!-- Regular menu items -->
              <el-menu-item 
                v-if="!item.children" 
                :index="item.path"
                :class="{ 'custom-active': activeMenuItem === item.path }"
              >
                <el-icon><component :is="item.icon" /></el-icon>
                <template #title>{{ item.label }}</template>
              </el-menu-item>
              
              <!-- Nested menu items -->
              <el-sub-menu 
                v-else 
                :index="item.id"
                popper-class="dark-submenu"
              >
                <template #title>
                  <el-icon><component :is="item.icon" /></el-icon>
                  <span>{{ item.label }}</span>
                </template>
                
                <el-menu-item 
                  v-for="child in item.children" 
                  :key="child.id" 
                  :index="child.path"
                  :class="{ 'custom-active': activeMenuItem === child.path }"
                >
                  <el-icon><component :is="child.icon" /></el-icon>
                  <template #title>{{ child.label }}</template>
                </el-menu-item>
              </el-sub-menu>
            </template>
          </el-menu>
        </el-aside>
        
        <!-- Main Content -->
        <el-container class="main-container">
          <!-- Breadcrumb Navigation -->
          <div class="breadcrumb-container">
            <div class="breadcrumb-left">
              <!-- 添加折叠按钮 -->
              <div class="collapse-btn" @click="isCollapse = !isCollapse">
                <el-icon :class="{ 'is-collapsed': isCollapse }">
                  <Fold v-if="!isCollapse" />
                  <Expand v-else />
                </el-icon>
              </div>
              
              <el-breadcrumb separator="/">
                <el-breadcrumb-item :to="{ path: breadcrumbItems[0].path }">
                  <div class="breadcrumb-item-content">
                    <el-icon><component :is="breadcrumbItems[0].icon" /></el-icon>
                    <span>{{ breadcrumbItems[0].label }}</span>
                  </div>
                </el-breadcrumb-item>
                <el-breadcrumb-item>
                  <span>{{ breadcrumbItems[1].label }}</span>
                </el-breadcrumb-item>
              </el-breadcrumb>
            </div>
            
            <!-- 添加头像区域 -->
            <div class="user-avatar">
              <el-dropdown trigger="click">
                <div class="avatar-wrapper">
                  <el-avatar :size="36" :src="userAvatar" />
                  <span class="user-name">{{ userName }}</span>
                  <el-tag size="small" type="info" class="user-role-tag">{{ userRole }}</el-tag>
                  <el-icon class="el-icon--right"><arrow-down /></el-icon>
                </div>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item>个人信息</el-dropdown-item>
                    <el-dropdown-item>修改密码</el-dropdown-item>
                    <el-dropdown-item v-if="hasPermission('*')" @click="navigateToUsers">
                      <el-icon style="margin-right: 5px;"><icon-user /></el-icon>
                      用户管理
                    </el-dropdown-item>
                    <el-dropdown-item v-if="hasPermission('*')" @click="navigateToRoles">
                      <el-icon style="margin-right: 5px;"><icon-user /></el-icon>
                      角色管理
                    </el-dropdown-item>
                    <el-dropdown-item v-if="hasPermission('*')" @click="navigateToOrganizations">
                      <el-icon style="margin-right: 5px;"><OfficeBuilding /></el-icon>
                      组织管理
                    </el-dropdown-item>
                    <el-dropdown-item divided @click="handleLogout">
                      <el-icon style="margin-right: 5px;"><switch-button /></el-icon>
                      退出登录
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>
          
          <el-main class="main-content">
            <TabsView />
          </el-main>
        </el-container>
      </el-container>
    </template>

    <!-- 登录页专用路由视图 -->
    <router-view v-if="isLoginPage" />
  </div>
</template>

<style>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html, body, #app {
  height: 100%;
  width: 100%;
  overflow: hidden;
  margin: 0;
  padding: 0;
}

.app-container {
  height: 100vh;
  width: 100vw;
}

.layout-container {
  height: 100vh;
  width: 100vw;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.sidebar {
  background-color: #D4E5F7;
  color: #2C3E50;
  height: 100%;
  overflow: hidden;
  transition: width 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.logo-container {
  height: 60px;
  line-height: 60px;
  text-align: center;
  border-bottom: 1px solid #E6F0FA;
  background-color: #E3F0FF;
  overflow: hidden;
  white-space: nowrap;
}

.logo-container h2 {
  margin: 0;
  color: #2C3E50;
  font-size: 1.5rem;
  font-weight: 600;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.sidebar-menu {
  border-right: none;
  height: calc(100% - 60px);
  background-color: #D4E5F7;
}

/* 修改菜单样式 */
.el-menu {
  border-right: none !important;
  background-color: transparent !important;
}

.sidebar-menu :deep(.el-menu-item) {
  height: 50px;
  line-height: 50px;
  color: #2C3E50 !important;
  background-color: transparent !important;
  margin: 4px 8px;
  border-radius: 4px;
  transition: all 0.3s ease;
}

/* 鼠标悬停时只改变文本颜色，不改变背景 */
.sidebar-menu :deep(.el-menu-item:hover) {
  background-color: transparent !important;
  color: #1890FF !important;
  font-weight: 500;
}

/* 明确禁用element-plus默认hover样式 */
.sidebar-menu :deep(.el-menu-item):hover:not(.is-active):not(.custom-active) {
  background-color: transparent !important;
}

/* 增强选择器权重，确保激活状态时的样式优先级最高 */
.sidebar-menu :deep(.el-menu-item.is-active),
.sidebar-menu :deep(.el-menu-item.is-active:hover),
.sidebar-menu :deep(.el-menu-item.custom-active),
.sidebar-menu :deep(.el-menu-item.custom-active:hover) {
  background-color: #1890FF !important;
  color: #FFFFFF !important;
  font-weight: 500;
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.6), 0 1px 3px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
  position: relative;
  z-index: 1;
}

/* 子菜单样式 */
.sidebar-menu :deep(.el-sub-menu) {
  background-color: transparent !important;
}

.sidebar-menu :deep(.el-sub-menu__title) {
  color: #2C3E50 !important;
  background-color: transparent !important;
  height: 50px !important;
  line-height: 50px !important;
  margin: 4px 8px !important;
  border-radius: 4px !important;
}

.sidebar-menu :deep(.el-sub-menu__title:hover) {
  background-color: transparent !important;
  color: #1890FF !important;
}

.sidebar-menu :deep(.el-sub-menu .el-menu) {
  background-color: #c4d9ef !important;
  padding: 4px;
  border-radius: 4px;
}

.sidebar-menu :deep(.el-sub-menu .el-menu-item) {
  background-color: transparent !important;
  margin: 2px 4px !important;
  border-radius: 4px !important;
  height: 40px !important;
  line-height: 40px !important;
}

/* 确保子菜单项有正确的激活状态样式 */
.sidebar-menu :deep(.el-sub-menu .el-menu-item.is-active),
.sidebar-menu :deep(.el-sub-menu .el-menu-item.custom-active) {
  background-color: #1890FF !important;
  color: #FFFFFF !important;
  font-weight: 500;
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.6), 0 1px 3px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
  position: relative;
  z-index: 1;
}

/* 子菜单图标对齐 */
.sidebar-menu :deep(.el-sub-menu .el-icon),
.sidebar-menu :deep(.el-menu-item .el-icon) {
  vertical-align: middle !important;
  margin-right: 8px !important;
}

.main-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.breadcrumb-container {
  padding: 0 20px;
  background-color: white;
  border-bottom: 1px solid #E6F0FA;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: space-between; /* 使面包屑和头像分布在两端 */
}

.breadcrumb-item-content {
  display: flex;
  align-items: center;
}

.el-breadcrumb__item {
  display: flex;
  align-items: center;
  line-height: 1;
}

.el-breadcrumb__item .el-icon {
  margin-right: 4px;
  font-size: 16px;
  display: flex;
  align-items: center;
}

.el-breadcrumb__separator {
  margin: 0 6px;
  align-self: center;
}

.main-content {
  padding: 16px;
  background-color: #f5f7fa;
  height: calc(100vh - 80px);
  overflow: hidden;
  width: 100%;
}

.el-card {
  height: 100%;
}

.loading-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 300px;
}

.loading-container .el-icon {
  font-size: 2rem;
  margin-bottom: 10px;
}

.loading-text {
  color: #909399;
}

/* 添加头像相关样式 */
.user-avatar {
  display: flex;
  align-items: center;
  height: 100%;
}

.avatar-wrapper {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 0 8px;
  height: 100%;
  transition: background-color 0.3s;
}

.avatar-wrapper:hover {
  background-color: #f5f7fa;
}

.user-name {
  margin: 0 8px;
  font-size: 14px;
  color: #2C3E50;
}

.el-icon--right {
  font-size: 12px;
  color: #909399;
  margin-left: 4px;
}

/* 调整面包屑样式以适应新布局 */
.el-breadcrumb {
  flex: 1;
}

/* 全局添加按钮样式 */
:deep(.add-button), :deep(.el-button--primary) {
  padding: 8px 16px;
  height: 32px;
  line-height: 1;
}

:deep(.add-button .el-icon), :deep(.el-button--primary .el-icon) {
  margin-right: 4px;
  font-size: 14px;
}

/* 调整卡片头部样式 */
:deep(.el-card__header) {
  padding: 10px 20px;
  min-height: 48px;
  display: flex;
  align-items: center;
}

/* 添加折叠按钮样式 */
.breadcrumb-left {
  display: flex;
  align-items: center;
  gap: 16px;
  flex: 1;
}

.collapse-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  color: #2C3E50;
}

.collapse-btn:hover {
  background-color: #f0f7ff;
}

.collapse-btn .el-icon {
  font-size: 18px;
  transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.collapse-btn .el-icon.is-collapsed {
  transform: rotate(180deg);
}

/* 调整侧边栏过渡动画 */
.sidebar {
  transition: width 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.logo-container {
  overflow: hidden;
  white-space: nowrap;
}

.logo-container h2 {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

/* 调整菜单折叠时的样式 */
.el-menu--collapse {
  width: 64px;
}

.el-menu--collapse .el-menu-item {
  padding: 0 !important;
  justify-content: center;
}

.el-menu--collapse .el-menu-item .el-icon {
  margin: 0;
}

.user-role-tag {
  margin-left: 8px;
  text-transform: capitalize;
}
</style>
